<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021-04-30
 * Time: 17:44
 */
namespace app\admin\model\system;
use think\Model;

class SystemMenu extends Model
{
    protected $name = "system_menu";
    protected $pk = "id";
    public function getPidMenuList()
    {
        $list        = $this->field('id,pid,title')
            ->where([
                ['pid', '<>', 99999],
                ['status', '=', 1],
            ])
            ->select()
            ->toArray();
//        echo '<pre>';
//        print_r($list);
//        exit;
        $pidMenuList = $this->buildPidMenu(0, $list);
//        $pidMenuList = array_merge([[
//            'id'    => 0,
//            'pid'   => 0,
//            'title' => '顶级菜单',
//        ]], $pidMenuList);
        return $pidMenuList;
    }

    protected function buildPidMenu($pid, $list, $level = 0)
    {
        $newList = [];
        foreach ($list as $vo) {
            if ($vo['pid'] == $pid) {
                $level++;
                foreach ($newList as $v) {
                    if ($vo['pid'] == $v['pid'] && isset($v['level'])) {
                        $level = $v['level'];
                        break;
                    }
                }
                $vo['level'] = $level;
                if ($level >= 1) {
                    $repeatString = "&nbsp;";
                    $markString   = str_repeat("{$repeatString}├{$repeatString}", $level - 1);
                    $vo['title']  = $markString . $vo['title'];
                }
                $newList[] = $vo;
                $childList = $this->buildPidMenu($vo['id'], $list, $level);
                !empty($childList) && $newList = array_merge($newList, $childList);
            }

        }
        return $newList;
    }
}